package com.blqy.fr.log.controller;


import com.blqy.fr.common.result.Result;
import com.blqy.fr.log.config.MinioConstantProperties;
import io.minio.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("/api/log")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;


    @GetMapping("/file")
    public String file() {
        return "hello minio";
    }
    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file) {

        try {
            //构造MinIO Client
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecretKey())
                    .build();

            //创建hello-minio桶
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                //创建hello-minio桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
                //设置hello-minio桶的访问权限
                String policy = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::sph/*"
                          } ],
                          "Version" : "2012-10-17"
                        }""";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioConstantProperties.getBucketName()).config(policy).build());
            } else {
                System.out.println("Bucket '" + minioConstantProperties.getBucketName() + "' already exists.");
            }

            //上传图片
//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket(minioConstantProperties.getBucketName())
//                            .object("公寓-外观.jpg") //uuid .jpg  .png
//                            .filename("D:\\workspace\\hello-minio\\src\\main\\resources\\公寓-外观.jpg")
//                            .build());
            String originalFilename = file.getOriginalFilename(); //公寓.adafadsfa.外观.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extName;//adfadf-adfad-fadf.png

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()) // image/jpg
                    .build());

            System.out.println("上传成功");
            //http://192.168.26.24:9000/sph/0a9ce384-87e8-499f-935e-d21b159ea209.jpg
            String filePath = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fileName;
            return Result.ok(filePath);
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
            throw new RuntimeException(e.getMessage());
        }
    }


//    @PostMapping("/fileUpload")
//    public Result<String> fileUpload(MultipartFile file) {
//
//        try {
//            //构造MinIO Client
//            MinioClient minioClient = MinioClient.builder()
//                    .endpoint(minioConstantProperties.getEndpointUrl())
//                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecretKey())
//                    .build();
//
//            //创建hello-minio桶
//            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
//            if (!found) {
//                //创建hello-minio桶
//                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
//                //设置hello-minio桶的访问权限
//                String policy = String.format("""
//                        {
//                          "Statement" : [ {
//                            "Action" : "s3:GetObject",
//                            "Effect" : "Allow",
//                            "Principal" : "*",
//                            "Resource" : "arn:aws:s3:::%s/*"
//                          } ],
//                          "Version" : "2012-10-17"
//                        }""", minioConstantProperties.getBucketName());
//                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioConstantProperties.getBucketName()).config(policy).build());
//            } else {
//                System.out.println("Bucket '" + minioConstantProperties.getBucketName() + "' already exists.");
//            }
//
//            // 3.把文件对象上传到对应的桶
//            String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
//            minioClient.putObject(PutObjectArgs.builder()
//                    .bucket(minioConstantProperties.getBucketName())
//                    .object(fileName)
//                    .stream(file.getInputStream(), file.getSize(), -1)
//                    .contentType(file.getContentType())
//                    .build());
//            return Result.ok(minioConstantProperties.getEndpointUrl()+"/" + minioConstantProperties.getBucketName() + "/" + fileName);
//        } catch (Exception e) {
//            System.out.println("Error occurred: " + e);
//            throw new RuntimeException(e.getMessage());
//        }
//    }
}


